﻿using System;
using System.Management.Automation;
using BGShell.PowerShell.Commands;

namespace BGShell.PowerShell.TabExpansion.Handlers
{
    internal sealed class CommandNameHandler : TabExpansionHandler
    {
        public CommandNameHandler(GetTabExpansionCommand command)
            : base(command)
        {
        }

        public override bool TryExpand(string line, string word)
        {
            var slash = word.IndexOf('\\');
            var includeSnapin = slash > -1;

            if (slash == 0)
            {
                // word = '\blah' 
                // definitely is not a command, but a root-relative
                // namespace path. keep looking.

                return true;
            }

            String snapinName = null;
            PSSnapInInfo snapin = null;

            if (includeSnapin)
            {
                includeSnapin = false;

                var snapinPattern = word.Substring(0, slash);

                if (!string.IsNullOrEmpty(snapinPattern))
                {
                    var snapins = InvokeArgs("Microsoft.PowerShell.Core\\Get-PSSnapIn -Name $args[0]", snapinPattern);

                    if ((snapins != null) && (snapins.Count > 0))
                    {
                        snapin = snapins[0].BaseObject as PSSnapInInfo;

                        if (snapin != null)
                        {
                            snapinName = snapin.Name + '\\';
                            includeSnapin = true;
                        }
                    }
                }
            }

            var commandNames = Command.InvokeCommand.GetCommandName(word + '*', true, false);

            if (includeSnapin)
            {
                for (int i = 0; i < commandNames.Count; i++)
                {
                    commandNames[i] = snapinName + commandNames[i];
                }
            }

            WriteExpansions(commandNames);
            return !includeSnapin;
        }
    }
}
